package com.yan.qing.bootoss.pojo;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;

import com.yan.qing.bootoss.constant.OssConstant;
import com.yan.qing.bootoss.util.OSSHepler;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.util.Objects;

/**
 */
@Slf4j
@Getter
public class AliOssInstance {

    public static AliOssInstance getInstance(AliOssProperties properties, InputStream inputStream, String filePath, String fileName) {
        return new AliOssInstance(properties, inputStream, filePath, StrUtil.blankToDefault(fileName, OSSHepler.generateFileName("")));
    }
    public static AliOssInstance getInstance(AliOssProperties properties, InputStream inputStream, String filePath) {
        return getInstance(properties, inputStream, filePath, null);
    }
    public static AliOssInstance getInstance(AliOssProperties properties, InputStream inputStream) {
        return getInstance(properties, inputStream, OssConstant.DEFAULT_FILE_PATH);
    }

    private OSSClient ossClient;
    private InputStream inputStream;
    private String filePath;
    private String fileName;
    private String fileUri;
    private AliOssProperties properties;

    private AliOssInstance(AliOssProperties properties, InputStream inputStream, String filePath, String fileName) {
        this.properties = properties;
        this.inputStream = inputStream;
        this.filePath = filePath;
        this.fileName = fileName;
    }

    public String getFileUri() {
        if (StrUtil.isBlank(fileUri)) {
            fileUri = StrUtil.concat(true, filePath.startsWith("/") ? filePath.substring(1) : filePath, fileName);
        }
        return fileUri;
    }

    public AliOssInstance upload() {
        try {
            if (Objects.isNull(ossClient)) {
                // TODO 后续优化改成连接池
                ossClient = new OSSClient(properties.getEndpoint(), new DefaultCredentialProvider(properties.getAccessKeyId(), properties.getAccessKeySecret()), null);
            }
            ossClient.putObject(properties.getBucketName(), getFileUri(), inputStream);

            return this;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("");
        } finally {
            IoUtil.close(inputStream);
        }
    }

    public String getFullUri(String host) {
        return StrUtil.concat(true, host, getFileUri());
    }

    public String getFullUri() {
        return getFullUri(properties.getDomain() + "/");
    }

}
